import os
from torchvision import transforms, models
from PIL import Image
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torchvision
import torch.nn as nn
import torch
from util.common import *

def train(net, train_iter, test_iter, num_epochs, lr, device):
    """
    Defined in :numref:`sec_lenet`"""
    def init_weights(m):
        if type(m) == nn.Linear or type(m) == nn.Conv2d:
            nn.init.xavier_uniform_(m.weight)
    net.apply(init_weights)
    print('training on', device)
    net.to(device)
    optimizer = torch.optim.Adam(net.parameters(), lr=lr)
    loss = nn.CrossEntropyLoss()
    animator = Animator(xlabel='epoch', xlim=[1, num_epochs],
                            legend=['train loss', 'train acc', 'test acc'])
    timer, num_batches = Timer(), len(train_iter)
    for epoch in range(num_epochs):
        # 训练损失之和，训练准确率之和，样本数
        metric = Accumulator(3)
        net.train()
        for i, (X, y) in enumerate(train_iter):
            timer.start()
            optimizer.zero_grad()
            X, y = X.to(device), y.to(device)
            y_hat = net(X)
            l = loss(y_hat, y)
            l.backward()
            optimizer.step()
            with torch.no_grad():
                metric.add(l * X.shape[0], accuracy(y_hat, y), X.shape[0])
            timer.stop()
            train_l = metric[0] / metric[2]
            train_acc = metric[1] / metric[2]
            if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
                animator.add(epoch + (i + 1) / num_batches,
                             (train_l, train_acc, None))
        test_acc = evaluate_accuracy_gpu(net, test_iter)
        animator.add(epoch + 1, (None, None, test_acc))
    print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
          f'test acc {test_acc:.3f}')
    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
          f'on {str(device)}')
    torch.save(net.state_dict(), 'resnet18.pth')
if __name__ == "__main__":
    #准备数据
    root = r'/home/luoluoluo/data/dataset/service_area'
    train_transform = transforms.Compose([
        transforms.Resize((128, 128)),
        transforms.RandomHorizontalFlip(),
        # transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
        transforms.ToTensor()
    ])
    test_transform = transforms.Compose([
        transforms.Resize((128, 128)),
        # transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        transforms.ToTensor(),
    ])
    # 使用torchvision.datasets.ImageFolder读取数据集 指定train 和 test文件夹
    train_data = torchvision.datasets.ImageFolder(os.path.join(root, "train"), transform=train_transform)
    train_iter = torch.utils.data.DataLoader(train_data, batch_size=8, shuffle=True, num_workers=0)
    test_data = torchvision.datasets.ImageFolder(os.path.join(root, "test"), transform=test_transform)
    test_iter = torch.utils.data.DataLoader(test_data, batch_size=8, shuffle=True, num_workers=0)

    # 准备模型
    net = models.resnet18()
    net.fc = nn.Linear(net.fc.in_features, 2)
    lr, num_epochs, batch_size = 0.001, 20, 8

    #开始训练
    train(net, train_iter, test_iter, num_epochs, lr, try_gpu())
